package com.wq.concurrency.basic;

import java.util.concurrent.*;

/**
 * @Author: wangqiang20995
 * @Date:2018/8/10
 * @Description:
 * @Resource:
 */
public class CountDownLatchTask {

    private CountDownLatch countDownLatch;

    private ExecutorService executor;

    private int totalTask;

    private Object monitor;

    private int number ;

    public CountDownLatchTask(int blockTasks,int poolSize){
        countDownLatch = new CountDownLatch(blockTasks);
        if(poolSize > 0) {
            executor = Executors.newFixedThreadPool(poolSize);
        }else {
            executor = Executors.newFixedThreadPool(Integer.MAX_VALUE);
        }
        this.totalTask = blockTasks;
        this.number = 0;
        this.monitor = new Object();
    }

    public void work(){
        long startTime = System.currentTimeMillis();
        long endTime;
        for(int i = 0; i < this.totalTask ; i++){
            Thread thread = new Thread(() -> {
                String threadName = Thread.currentThread().getName();
                System.out.println("["+threadName+"] sleep 1s");
                try {
//                    synchronized (monitor) {
                        TimeUnit.SECONDS.sleep(1);
                        System.out.println("[" + threadName + "] start work and number is --> " + number);
                        number++;
                        System.out.println("[" + threadName + "] work number --> " + number);
//                    }
                    this.countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            thread.setName("Thread-" + (i));
            this.executor.execute(thread);
        }
        try {
            this.countDownLatch.await();
//            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            endTime = System.currentTimeMillis();
        }

        System.out.println("totalTime --> " + (endTime - startTime) + " and number --> " + number);

        this.executor.shutdown();
    }

    public static void main(String args[]){
        CountDownLatchTask task = new CountDownLatchTask(10,15);
        task.work();
    }
}
